import { getPosIDs, getPosName, getUserID, getUserName } from '@/utils';
import { Empty, message, Spin } from 'antd';
import {
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from 'react';
import { WorkflowSwitchContext } from '../common';
import {
  getTaskNodes,
  getUserListByOrgSrv,
  procdefDataGridServices,
} from '../services';
import { WorkflowNodesTable } from './WorkflowNodesTable';
import _ from 'lodash';
import React from 'react';
import { WorkflowSwitchAPI } from '../common/type';

export const WorkflowNodesView = React.forwardRef<
  WorkflowSwitchAPI.IWorkflowNodesViewRef,
  WorkflowSwitchAPI.IWorkflowNodesView
>(
  (
    {
      switchFlowObj, //选中的非默认流程 id
      changeProcessID, //保存当前展示的默认流程 id  给查看流程图使用
    },
    ref,
  ) => {
    const {
      requestController,
      orderType,
      category,
      businessCategory,
      businessInfoObj,
    } = useContext(WorkflowSwitchContext);

    /**
     * 导出Ref 数据
     */
    useImperativeHandle(ref, () => ({
      workflowNodesList: workFlowNodesListMemo,
    }));

    /**
     * 保存 节点之间的数据
     */
    const [workFlowNodes, setWorkFlowNodes] = useState<Record<string, any>[]>(
      [],
    );

    /**
     * 获取用户信息回调
     * @param res
     */
    const loadUserByPosCallBack = (res: any) => {
      if (!(res && res?.msgFlag)) {
        message.error(res?.msg);
      }
    };

    /**
     *  获取用户信息
     */
    const { loadUserRun, loadUserLoading, loadUserData } = getUserListByOrgSrv(
      loadUserByPosCallBack,
    );

    /**
     * 处理节点间用户数据会签和普通
     */
    const handNodeUserList = (
      dealerKey: string[],
      dealerName: string[],
      dealerType: number,
    ) => {
      let allList: Record<string, any>[] = [];
      let obj: Record<string, any> = {};
      dealerKey?.forEach((itemKey: any, index: number) => {
        let [postKey, userKey]: string[] = itemKey?.split('|');
        let [postName, userName]: string[] = dealerName?.[index]?.split('|');
        if (dealerType == 0) {
          const objLabelKey: string = `${postKey}_${postName}`;
          let userObj: Record<string, any> = {
            userID: userKey,
            userName: userName,
          };
          obj[objLabelKey] = obj?.[objLabelKey]
            ? [...obj[objLabelKey], userObj]
            : [userObj];
        } else if (dealerType == 1) {
          let [postKey, userKey]: string[] = itemKey?.split('|');
          let [postName, userName]: string[] = dealerName?.[index]?.split('|');
          let obj: Record<string, any> = {
            postId: postKey,
            postName: postName,
            defaultDealer: userKey,
            defaultDealerName: userName,
          };
          allList?.push(obj);
        }
      });

      if (obj && JSON.stringify(obj) != '{}' && dealerType == 0) {
        Object.keys(obj)?.forEach((posItem: any, posIndex: number) => {
          const [postId, postName]: string[] = posItem?.split('_');
          let newObj: Record<string, any> = {
            postId,
            postName,
            defaultDealer: obj?.[posItem]?.[0]?.userID,
            defaultDealerName: obj?.[posItem]?.[0]?.userName,
            userList: obj?.[posItem],
          };

          allList?.push(newObj);
        });
      }
      return allList;
    };

    /**
     * 处理每个节点的岗位数据
     * @param nodeInfoObj
     * @returns
     */
    const handlePostList = (
      nodeInfoObj: Record<string, any>,
      nodeInfoIndex: number,
    ) => {
      const postKeyList: string[] = nodeInfoObj?.dealPositionID
        ? nodeInfoObj?.dealPositionID
            ?.split(',')
            ?.filter((itemKey: any) => itemKey)
        : [];
      // const postKeyListName: string[] = nodeInfoObj?.dealPositionName ? nodeInfoObj?.dealPositionName?.split(',')?.filter((itemName: any) => itemName) : [];

      let postDateList: Record<string, any>[] = []; //存储节点岗位数据

      let postDateKeys: string[] | any = []; //存储节点 岗位 id
      let newUserList: string[] | any = []; //存储节点 用户 id

      if (nodeInfoObj?.dealPositionID == 'originPositionID,') {
        let postList: Record<string, any> = {
          postId: getPosIDs(),
          postName: getPosName(),
          defaultDealer: getUserID(),
          defaultDealerName: getUserName(),
        };
        postDateList?.push(postList);
        postDateKeys?.push(getPosIDs());
      } else {
        /**
         * 获取到处理人的数据
         */
        let userListKey: string[] = nodeInfoObj?.postDealerID
          ? nodeInfoObj?.postDealerID
              ?.split(',')
              ?.filter((itemUserKey: any) => itemUserKey)
          : [];
        let userListName: string[] = nodeInfoObj?.postDealerName
          ? nodeInfoObj?.postDealerName
              ?.split(',')
              ?.filter((itemUserName: any) => itemUserName)
          : [];

        newUserList = handNodeUserList(
          userListKey,
          userListName,
          nodeInfoObj?.taskIsSign,
        );

        postDateList?.push(...newUserList);
        postDateKeys?.push([...postKeyList]);
      }
      return {
        postDateList,
        postDateKeys,
        newUserList,
      };
    };

    /**
     * 流程节点回调
     * @param res
     */
    const taskNodesCallBack = (res: any) => {
      if (res && res?.msgFlag) {
        if (res?.obj && res?.obj?.length > 0) {
          let postIDs: string[] | any = []; //保存所有岗位 id

          /**
           * 处理数据
           * @param dataList
           * @returns
           */
          let loopMapPost = (dataList: Record<string, any>[]) => {
            return dataList?.map((item: any, index: number) => {
              const {
                postDateList,
                postDateKeys,
                newUserList,
              } = handlePostList(item, index);
              postIDs?.push(...postDateKeys);
              return {
                ...item,
                postValues: postDateList,
                allUserValues: newUserList,
              };
            });
          };
          const postUserList = loopMapPost(res?.obj); // 返回的数据 没有 objJson
          setWorkFlowNodes(postUserList);

          let removalPosts = Array.from(new Set(postIDs)); //去重 岗位 id
          if (removalPosts && removalPosts?.length > 0) {
            let postIDsStr: string = removalPosts?.toString();
            loadUserRun(postIDsStr);
          }
        }
      }
    };

    /**
     * 流程节点
     */
    const { taskNodesRun, taskNodesLoading } = getTaskNodes(
      taskNodesCallBack,
      requestController,
    );

    /**
     * 流程列表接口回调
     * @param res
     */
    const procdefDataCallback = (res: any) => {
      if (res && res?.msgFlag) {
        if (res && res?.rows && res?.rows?.length > 0) {
          let nodeParams: Record<string, any> = {
            businessID: businessInfoObj?.id, //业务工单ID
          };
          let dataDefaultObj: Record<string, any> | any = res?.rows?.find(
            (item: any) => {
              return item.isDefault == '1';
            },
          );
          if (dataDefaultObj && dataDefaultObj?.id) {
            nodeParams['processID'] = dataDefaultObj?.id; //流程ID
          } else {
            nodeParams['processID'] = res?.rows?.[0]?.id;
          }

          changeProcessID(nodeParams['processID']);

          taskNodesRun(nodeParams);
        }
      } else {
        message.error(res?.msg);
      }
    };

    /**
     * 获取流程列表
     */
    const { getProcdefData, pageLoading } = procdefDataGridServices(
      procdefDataCallback,
      requestController,
    );

    /**
     * 处理岗位 和接口中的人员挂钩
     */
    const handPostAndUserList = (
      curItemObj: Record<string, any>,
      postList: Record<string, any>[],
    ) => {
      let newPostList: Record<string, any>[] = [];
      postList?.forEach((postItem: Record<string, any>) => {
        newPostList?.push({
          ...postItem,
          checkUserList:
            curItemObj?.taskIsSign == 0
              ? null
              : loadUserData?.[postItem?.postId],
        });
      });
      return newPostList;
    };

    /**
     * 保保存 普通节点id 对饮选中 的岗位
     */
    const [ordinaryUserInfoObj, setOrdinaryUserInfoObj] = useState<
      Record<string, any>
    >({});

    /**
     * 岗位和人员节点处理
     */
    const workFlowNodesListMemo = useMemo(() => {
      let nodesList: Record<string, any>[] = [];
      if (
        workFlowNodes &&
        workFlowNodes?.length > 0 &&
        loadUserData &&
        JSON.stringify(loadUserData) != '{}'
      ) {
        let postCheckInfo: Record<string, any> = {}; //保存 普通节点id 对饮选中 的岗位

        workFlowNodes?.forEach((pItem: any, pIndex: number) => {
          nodesList[pIndex] = {
            ...pItem,
            postValues:
              pItem?.dealPositionID == 'originPositionID,'
                ? pItem?.postValues
                : handPostAndUserList(pItem, pItem?.postValues),
          };
          if (
            pItem?.dealPositionID != 'originPositionID,' &&
            pItem?.taskIsSign == 0
          ) {
            const checkPostIdObj = pItem?.taskNode;
            postCheckInfo[checkPostIdObj] = pItem?.postValues?.[0]?.postId;
          }
        });

        setOrdinaryUserInfoObj(postCheckInfo);
      }

      return nodesList;
    }, [workFlowNodes, loadUserData]);

    /**
     * 初始化
     */
    useEffect(() => {
      if (switchFlowObj?.processID) {
        let nodeParams: Record<string, any> = {
          businessID: businessInfoObj?.id, //业务工单ID
          processID: switchFlowObj?.processID,
        };
        taskNodesRun(nodeParams);
      } else {
        let params: Record<string, any> = {
          orderType: orderType, //工单类型
          category: category, //业务流程类别
          businessCategory: businessCategory, // 总 流程类别
          pageSize: 1000,
          current: 1,
          suspendState: '1',
        };
        getProcdefData(params);
      }
    }, [switchFlowObj?.processID]);

    return (
      <Spin spinning={loadUserLoading || taskNodesLoading || pageLoading}>
        {workFlowNodesListMemo && workFlowNodesListMemo?.length > 0 ? (
          <WorkflowNodesTable
            workFlowNodesList={workFlowNodesListMemo}
            userDataInfoObj={loadUserData}
            ordinaryUserInfoObj={ordinaryUserInfoObj}
            changePostCheckID={(selectKey: string, selectValue: string) => {
              let changePostIdInfo: Record<string, any> = _.cloneDeep(
                ordinaryUserInfoObj,
              );
              changePostIdInfo[selectKey] = selectValue;
              setOrdinaryUserInfoObj(changePostIdInfo);
            }}
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="暂无流程节点信息！"
          />
        )}
      </Spin>
    );
  },
);
